#include "window.h"

#include "gl.h"
#include "buttons.h"

#include "../gvl/system/system.hpp"

typedef struct flip_window_internal_common_
{
	flip_window* parent;
	uint width, height;
	int fullscreen;
	flip_point mouse_pos;
	
	// FPS throttling
	uint32_t prev_frame_ms;
	
	char button_state[flip_numButtons + 1];
} flip_window_internal_common;

#define PIMPL (*(flip_window_internal_common*)self->internal_)

void flip_window_internal_common_init(flip_window_internal_common* self)
{
	int i;
	self->mouse_pos.x = 0;
	self->mouse_pos.y = 0;
	for(i = 0; i < flip_numButtons; ++i)
		self->button_state[i] = 0;
		
	self->width = 0;
	self->height = 0;
	self->fullscreen = 0;
	self->prev_frame_ms = gvl_get_ticks();
}

void flip_window_internal_setup_gl(flip_window_internal_common* self)
{
	int width = flip_window_width(self->parent);
	int height = flip_window_height(self->parent);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glViewport(0, 0, width, height);
	glOrtho(0.0, width,
		 height,
		 0.0,
		 -100.0,
		 100.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	glClearColor(0.15f, 0.15f, 0.4f, 1.0f);
	glClearDepth(1.0f);
	
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_TEXTURE_2D);
}


void flip_window_force_button(flip_window* self, int id, int down, int collect_event)
{
	if(id < 0)
		return;
		
	PIMPL.button_state[id] = down;
	if(collect_event)
	{
		if(self->handlers.button)
			self->handlers.button(self, id, down);
	}

}

void flip_window_set_button(flip_window* self, int id, int down, int collect_event)
{
	if(id < 0)
		return;
		
    if(PIMPL.button_state[id] != down)
        flip_window_force_button(self, id, down, collect_event);
}

#undef PIMPL
